/*global $Client*/
import React, { useState, useEffect, useRef, useCallback } from "react";
import { Spin, message, Button } from "antd";
import { ListTable, Menu, ListColumn } from "@visactor/react-vtable";
import { ExportOutlined } from "@ant-design/icons";
import { downloadExcel, exportVTableToExcel } from "@visactor/vtable-export";
import * as VTable from "@visactor/vtable";
import * as VTable_editors from "@visactor/vtable-editors";
import { round } from 'mathjs'
import {customPrompt } from '../assembly/customprompt'

const input_editor = new VTable_editors.InputEditor();
VTable.register.editor("input-editor", input_editor);



//报关单明细批量操作
const App = (pagedata) => {
  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState(null);
  const tableInstance = useRef(null);
  const [messageApi, contextHolder] = message.useMessage();

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      console.log("pagedata", pagedata);
      const Subform_Detail = pagedata?.data?.data?.Subform_Detail;
      // Subform_Detail.forEach((item) => {
      //   item.PdName = item?.Product?.name;
      // });

      console.log("DeclarationSubfrom", Subform_Detail);

      if (Subform_Detail) {
        setRecords(Subform_Detail);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  }, [pagedata]);

  // 在组件加载时调用 fetchData
  useEffect(() => {
    const initialize = async () => {
      await window.zohoReadyPromise;
      console.log("ZOHO is ready", window.ZOHO);
      fetchData();
    };
    initialize();
  }, [fetchData]);




  const onDropdownMenuClick = async (args) => {
    try{
      if (args.text === "按照此条件过滤") {
        console.log("按照此条件过滤");
  
        var titlename = tableInstance.current.getHeaderField(args.col, args.row);
        var cellValue = tableInstance.current.getCellValue(args.col, args.row);
        if (!cellValue) {
          messageApi.info("所选单元格值为空!");
          return;
        }
        tableInstance.current.updateFilterRules([
          {
            filterKey: titlename,
            filteredValues: cellValue,
          },
        ]);
      } else if (args.text === "清除过滤条件") {
        console.log("清除过滤条件");
        tableInstance.current.updateFilterRules();
      } else if (args.text === "批量修改") {
        let selectCells = tableInstance.current.getSelectedCellInfos();
  
        console.log(selectCells);
        if (!checkColumns(selectCells)) {
          messageApi.info("只能批量修改同一列的数据!");
          return;
        }
        // 获取列的字段名
      const colField = tableInstance.current.getHeaderField(selectCells[0][0].col, selectCells[0][0].row);
      
      // 从 option.columns 中找到对应的列配置
      const columnConfig = option.columns.find(column => column.field === colField);
      
      // 检查该列是否有 editor 属性，并且等于 "input-editor"
      if (!columnConfig || columnConfig.editor !== "input-editor") {
        messageApi.info("所选字段不可编辑!");
        return;
      }
        // const userInput = prompt("请输入值:", "");
        const userInput = await customPrompt("请输入值:");
        
        console.log("userInput", userInput);
        console.log("selectCells", selectCells);
        if (userInput !== null) {
          selectCells.forEach((item) => {
            tableInstance.current.changeCellValue(item[0].col, item[0].row, userInput);
          });
        }
  
      }
    }catch (error) {
      console.error("Error:", error);
    }
  };


  const ready = (instance, isInitial) => {
    if (isInitial) {
      tableInstance.current = instance;
    }
  };
  const checkColumns = (array) => {
    // 获取所有子数组的 col 值
    const cols = array.map((subArray) =>
      subArray.length === 1 ? subArray[0].col : null
    );

    // 过滤掉 null 值
    const filteredCols = cols.filter((col) => col !== null);

    // 检查所有 col 值是否相同
    const allEqual = filteredCols.every((col) => col === filteredCols[0]);

    return allEqual && filteredCols.length === array.length;
  };
  const option = {
    columns: [
      {
        field: "LinkingModule5_Serial_Number",
        title: "序号",
        width: "auto",
        aggregation: {
          aggregationType: VTable.TYPES.AggregationType.NONE,
          formatFun(value) {
            return "合计:";
          },
        },
      },
      {
        field: "OrderNo",
        title: "订单号",
        width: "auto",
        editor: "input-editor",
      },
      {
        field: "ContainerNumber",
        title: "集装箱号",
        width: "auto",
        editor: "input-editor",
        // disableSelect: true,
      },
      {
        field: "BoxNum",
        title: "箱号",
        width: "auto",
        editor: "input-editor",
      },
      { field: "ShippingMark", title: "唛头", width: "auto" },
      { field: "Englishname", title: "英文品名", width: "auto" },
      { field: "Product.name", title: "商品编码", width: "auto" },
      { field: "AccountprtNo", title: "客户货号", width: "auto",editor: "input-editor", },
      { field: "internalcode", title: "内部货号", width: "auto" },
      { field: "Englishname", title: "英文品名", width: "auto" },
      { field: "Specification", title: "英文规格", width: "auto" },
      { field: "Productname", title: "中文品名", width: "auto" },
      { field: "Chinesespecification", title: "中文规格", width: "auto" },
      { field: "ChinesePackagedesp", title: "包装描述", width: "auto" },
      { field: "Chineseingredients", title: "成份", width: "auto" },
      { field: "Chptrequirements_material", title: "生产要求(材质)", width: "auto" },
      {
        field: "Qty",
        title: "销售数量",
        width: "auto",
        aggregation: {
          aggregationType: VTable.TYPES.AggregationType.SUM,
          formatFun(value) {
            return round(value, 2);
          },
        },
      },
      { field: "SalesAmount", title: "销售金额", width: "auto" },
      { field: "Brand", title: "品牌", width: "auto" },
      { field: "Unit", title: "单位", width: "auto" },
      { field: "Unit_Price", title: "单价 (USD)", width: "auto" },
      { field: "SalesAmount", title: "销售金额", width: "auto" },
      { field: "Nuofboxeinnerbox", title: "内盒数", width: "auto" },
      { field: "Nuofboxesinpg", title: "入数", width: "auto" },
      { field: "Lengthofouterbox", title: "长(CM)", width: "auto" },
      { field: "Cartonwidth", title: "宽(CM)	", width: "auto" },
      { field: "Heightofouterbox", title: "高(CM)	", width: "auto" },
      { field: "Volume", title: "体积", width: "auto" },
      { field: "Grossweight", title: "毛重", width: "auto",editor: "input-editor"},
      { field: "Netweight", title: "净重", width: "auto" },
      { field: "Packaginunit", title: "包装单位", width: "auto" },
      {
        field: "QuantityperCarton",
        title: "每箱装量",
        width: "auto",
        aggregation: {
          aggregationType: VTable.TYPES.AggregationType.SUM,
          formatFun(value) {
            return round(value, 2);
          },
        },
      },
      { field: "NumberofCartons", title: "箱数", width: "auto" },
      {
        field: "TotalGrossWeight",
        title: "总毛重",
        width: "auto",
        aggregation: {
          aggregationType: VTable.TYPES.AggregationType.SUM,
          formatFun(value) {
            return round(value, 2);
          },
        },
      },
      {
        field: "TotalNetWeight",
        title: "总净重",
        width: "auto",
        aggregation: {
          aggregationType: VTable.TYPES.AggregationType.SUM,
          formatFun(value) {
            return round(value, 2);
          },
        },
      },
      {
        field: "TotalVolume",
        title: "总体积",
        width: "auto",
        aggregation: {
          aggregationType: VTable.TYPES.AggregationType.SUM,
          formatFun(value) {
            return round(value, 2);
          },
        },
      },
      { field: "HSCode", title: "HSCode", width: "auto" },
      { field: "PSNoticeNo", title: "生产通知单号", width: "auto" },
      { field: "ForeignsacontractNo", title: "外销合同号", width: "auto" },
      { field: "PurchaseTaxRate", title: "进价税率", width: "auto" },
      { field: "RefundTaxRate", title: "退税率", width: "auto" },
      { field: "Ratio", title: "配比", width: "auto" },
      { field: "ProductCategory", title: "产品大类", width: "auto" },
      { field: "ClearanceCurrency", title: "清关币种", width: "auto" },
      { field: "StocknoticeNo", title: "备货单号", width: "auto" },
      { field: "BatchNumber", title: "批次号", width: "auto" },
      { field: "Batch", title: "批号", width: "auto" },
      { field: "Tastingperiod", title: "尝味期", width: "auto" },
      { field: "field1", title: "清关单价 (USD)", width: "auto" },
    ],
  };

  const handtooltipfeilds = [
    "Qty",
    "UnitPrice",
    "UnitNotPrice",
    "DeclarationAmount",
    "TotalGrossWeight",
    "TotalNetWeight",
    "TotalVolume",
    "QuantityperCarton",
  ];

  const success = async () => {
    setLoading(true);
    try{
      tableInstance.current.updateFilterRules();

      console.log("tableInstance.current", tableInstance.current.records);
      $Client.close({data_updata: tableInstance.current.records});
      
    }catch (error) {
      
    }finally{
      setLoading(false);
    }

  };
  const cancel = async () => {
    $Client.close();

  };
  const handleExport = async () => {
    if (tableInstance.current) {
      downloadExcel(await exportVTableToExcel(tableInstance.current), "export");
    } else {
      messageApi.info("没有数据可以导出！");
    }
  };

  const handTooltip = (args) => {
    const { col, row } = args;
    let selectCells = tableInstance.current.getSelectedCellInfos();
    var titlename = tableInstance.current.getHeaderField(col, row);

    if (
      checkColumns(selectCells) &&
      selectCells.length > 1 &&
      handtooltipfeilds.includes(titlename)
    ) {
      const valueSum = selectCells.reduce((sum, item) => {
        const value = parseFloat(item[0].value) || 0; // Ensure value is a number
        return sum + value;
      }, 0);

      const rect = tableInstance.current.getVisibleCellRangeRelativeRect({
        col,
        row,
      });
      tableInstance.current.showTooltip(col, row, {
        content: "小计：" + round(valueSum),
        referencePosition: { rect, placement: VTable.TYPES.Placement.bottom }, //TODO
        className: "defineTooltip",
        style: {
          bgColor: "white",
          color: "black",
          arrowMark: true,
        },
      });
    }
  };

  return (
    <div>
      {contextHolder}
      <Spin spinning={loading}>
        <div
          style={{
            display: "flex",
            justifyContent: "flex-end",
            gap: "10px",
            position: "fixed",
            top: 10,
            right: 10,
            zIndex: 9999,
          }}
        >
          <Button onClick={cancel}>
            取消
          </Button>
          <Button type="primary" onClick={success}>
            确定
          </Button>
          <Button
            type="primary"
            shape="circle"
            icon={<ExportOutlined />}
            onClick={handleExport}
          />
        </div>
        <div style={{ paddingTop: "50px" }}>
          <ListTable
            records={records}
            height={"500px"}
            widthMode="standard"
            theme={VTable.themes.ARCO}
            dragHeaderMode="column"
            onReady={ready}
            onMouseEnterCell={handTooltip}
            frozenColCount={4}
            bottomFrozenRowCount={1}
            onDropdownMenuClick={onDropdownMenuClick}
          >
            {option.columns.map((column) => (
              <ListColumn
                key={column.field}
                field={column.field}
                title={column.title}
                width={column.width}
                editor={column.editor}
                disableSelect={column.disableSelect}
                aggregation={column.aggregation}
              />
            ))}
            <Menu
              renderMode={"html"}
              contextMenuItems={["按照此条件过滤", "清除过滤条件", "批量修改"]}
            />
          </ListTable>
        </div>
      </Spin>
    </div>
  );
};

export default App;
